#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RocketMQ 5.1.0 简化发送消息示例
"""

import json
import time
from rocketmq.client import Producer, Message
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def send_message_to_rocketmq():
    """发送消息到RocketMQ的简单示例"""
    
    # RocketMQ连接配置
    namesrv_addr = "localhost:9876"  # NameServer地址
    access_key = "735cf4a8f557"      # ACL访问密钥
    secret_key = "Zjlab123!@#"       # ACL密钥
    group_name = "python_sender_group"
    topic = "test_topic"             # 主题名称
    
    producer = None
    
    try:
        # 1. 创建生产者
        logger.info("正在创建RocketMQ生产者...")
        producer = Producer(group_name)
        
        # 2. 设置NameServer地址
        producer.set_name_server_address(namesrv_addr)
        
        # 3. 设置ACL认证信息
        producer.set_session_credentials(access_key, secret_key, "ALIYUN")
        
        # 4. 启动生产者
        producer.start()
        logger.info("生产者启动成功！")
        
        # 5. 发送消息
        logger.info("开始发送消息...")
        
        for i in range(5):
            # 创建消息数据
            message_data = {
                "id": i + 1,
                "content": f"这是第{i + 1}条测试消息",
                "timestamp": int(time.time()),
                "sender": "python_client"
            }
            
            # 创建消息对象
            msg = Message(topic)
            msg.set_body(json.dumps(message_data, ensure_ascii=False).encode('utf-8'))
            msg.set_tags("test")  # 设置消息标签
            msg.set_keys(f"key_{i + 1}")  # 设置消息键
            
            # 发送同步消息
            send_result = producer.send_sync(msg)
            
            logger.info(f"消息 {i + 1} 发送成功 - MsgId: {send_result.msg_id}")
            
            # 等待1秒再发送下一条
            time.sleep(1)
        
        logger.info("所有消息发送完成！")
        
    except Exception as e:
        logger.error(f"发送消息失败: {e}")
        
    finally:
        # 关闭生产者
        if producer:
            producer.shutdown()
            logger.info("生产者已关闭")


if __name__ == "__main__":
    send_message_to_rocketmq() 